package vip.zhenzicheng.nettybasic.sharehandler;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.Random;

/**
 * @author zhenzicheng
 * @date 2022-06-08 19:09
 */
public class EchoClientMCHandler extends SimpleChannelInboundHandler<ByteBuf> {

  private Random r = new Random();


  @Override
  protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
    System.out.println("client accept：" + byteBuf.toString(CharsetUtil.UTF_8));
  }

  @Override
  public void channelActive(ChannelHandlerContext ctx) throws Exception {
    ByteBuf msg;
    String request = "Hello" + System.getProperty("line.separator");
    int sendCount = r.nextInt(10) + 1;
    for (int i = 0; i < sendCount; i++) {
      msg = Unpooled.buffer(request.length());
      msg.writeBytes(request.getBytes());
      ctx.writeAndFlush(msg);
    }

  }
}
